<template>
  <div ref="echartsRef" style="width: 100%; height: 100%;"></div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { merge } from 'lodash';

const props = defineProps<{
  option: Record<string, any>;
}>();

const defaultOption = {
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '2%',
    right: '0%',
    bottom: '6%',
    top: '14%',
    containLabel: true
  },
  legend: {
    bottom: 10,
    right: 20
  },
  xAxis: {
    type: 'category',
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#1D2129'
    },
    axisLine: {
      lineStyle: {
        color: '#E5E6EA'
      }
    }
  },
  yAxis: [{
    type: 'value',
    nameTextStyle: {
      color: '#1D2129',
      fontSize: 14
    },
    nameGap: 20,
    axisLabel: {
      color: '#1D2129'
    },
    axisLine: {
      lineStyle: {
        color: '#E5E6EA'
      }
    }
  },
  {
    position: 'right',
    nameTextStyle: {
      color: '#1D2129',
      fontSize: 14
    },
    nameGap: 20,
    axisLabel: {
      color: '#1D2129'
    },
    axisLine: {
      lineStyle: {
        color: '#E5E6EA'
      }
    },
    axisTick: {
      show: true,
      lineStyle: {
        color: '#E5E6EA'
      }
    },
    splitLine: {
      show: false
    }
  }],
  series: [{
    itemStyle: {
      // color: '#046AF9',
      borderRadius: [2, 2, 0, 0]
    }
  }]
};

const echartsRef = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;

onMounted(() => {
  chart = echarts.init(echartsRef.value as HTMLDivElement);
  const mergedOption = merge({}, defaultOption, props.option);
  chart.setOption(mergedOption);
  window.addEventListener('resize', resizeChart);
});

watch(() => props.option, (newOption) => {
  const mergedOption = merge({}, defaultOption, newOption);
  chart?.setOption(mergedOption);
}, { deep: true });

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart);
  chart?.dispose();
});

function resizeChart() {
  chart?.resize();
}
</script>